# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         platform.py
# Description:
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2020/9/17 17:42
# -------------------------------------------------------------------------------
from rest_framework import status
from rest_framework.generics import DestroyAPIView
from rest_framework.mixins import UpdateModelMixin
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet, GenericViewSet

from QAPlatform.mixins import CustomCreateModelMixin
from apps.MockService.filters import PlatformFilter
from apps.MockService.models import Platform, UrlMock
from apps.MockService.serializers import PlatformListSerializer, PlatformSerializer

__all__ = ['PlatformListViewSet', 'PlatformViewSet', 'PlatformDestroyAPIView']


class PlatformListViewSet(ReadOnlyModelViewSet):
    """
    平台列表
    """
    queryset = Platform.objects.filter(is_deleted=False)
    serializer_class = PlatformListSerializer
    filter_class = PlatformFilter


class PlatformViewSet(CustomCreateModelMixin, UpdateModelMixin, GenericViewSet):
    """
    平台创建、更新
    """
    queryset = Platform.objects.filter(is_deleted=False)
    serializer_class = PlatformSerializer


class PlatformDestroyAPIView(DestroyAPIView):
    """
    平台删除
    """

    def delete(self, request, *args, **kwargs):
        data = request.data
        platform_id = data.get('platform')
        if UrlMock.objects.filter(platform_id=platform_id, is_deleted=False):
            return Response(status=status.HTTP_200_OK, data='删除失败：该平台中存在UrlMock，不允许被删除',
                            content_type='application/json')

        Platform.objects.filter(id=platform_id).update(is_deleted=True)
        return Response(status=status.HTTP_204_NO_CONTENT, data='删除成功', content_type='application/json')
